/***
 * 手牌UI管理类
 */
var UtilGameObject = require('./../../FrameWork/Utils/UtilGameObject');
var _ = require('./../../FrameWork/we_underscore');
var ClientDelegate = require('./../../FrameWork/Delegate/ClientDelegate');
var ClientEveDelegate = require('./../../FrameWork/Delegate/ClientEveDelegate');
var ClientPkDelegateType = require('./../../PkCommon/Delegate/ClientPkDelegateType');
var PkSound = require('./../PkSound');
var FindAutoFilter = require('./../FindTool/FindAutoFilter');
var AIGetCard = require('../AI/Get/AIGetCard');
var AIOutCard = require('../AI/Out/AIOutCard');

var EnumOpBtn = require('./../../PkCommon/Enum/EnumOpBtn');
cc.Class({
    extends: ClientDelegate,

    properties: {
        prefabPkHandCard: {
            default: null,
            type: cc.Prefab,
            displayName: '扑克手牌预设'
        },
        mainLayer: {
            default: null,
            type: cc.Node,
        }
    },

    onLoad() {
        this.addListerDelegate(ClientPkDelegateType.Client_gamingBtn_Out, this._eveBtnOutCard.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_autoOutSelfCardAll, this.autoOutSelfCardAll.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_gamingBtn_tip, this._eveBtnTip.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_gamingBtn_noOut, this._eveBtnNoOut.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Clinet_sendFristCards, this.createHandCardItems.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Clinet_addBottomOneCardToHand, this.addBottomOneCardToHand.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_timeOutCardSelfCtr, this.timeOutCard.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Clinet_singleEndShowSelfHandCard, this.gameEndShowHandCards.bind(this));

        this.resetNet();
        //计算固定间距
        var tmpCnt = this._getCardCntMax() - this._getLimitCnt();
        /***铺满的实现 */
        var prefabSize = this._getPrefabSize();
        var needWidthTotal = this.mainLayer.width - prefabSize.width;
        this.fixedSpaceX = needWidthTotal / (tmpCnt - 1) * 1.05;
    },
    resetNet() {
        if (!!window.g_room) {
            this.lockTouchHand = false; //锁定手牌操作
            var selfSeat = window.g_room.getSelfSeat();
            var handCards = selfSeat.getHandCards();
            this.createHandCardItems(handCards, false);
            this._opCardCnt = null;
            this.findTipInfo = null;
        }
    },
    /**超时出牌 */
    timeOutCard(_cardsInfo) {
        var removeCtrList = this.removeCardCtrs(_cardsInfo);
        this.resetSortByCtr();
        this.actResetSortUI();
        ClientEveDelegate.doDataToLister(ClientPkDelegateType.Clinet_gamingBtnsState, EnumOpBtn.NONE); //关闭隐藏操作按钮
        ClientEveDelegate.doDataToLister(ClientPkDelegateType.Client_outSelfCtr, removeCtrList);
        this.findTipInfo = null;
        this._opCardCnt = null;
    },
    gameEndShowHandCards() {
        if (null != this.ctrSelfList && _.size(this.ctrSelfList) > 0) {
            _.each(this.ctrSelfList, function(_ctr) {
                _ctr.setCanTouch(false);
            });
            ClientEveDelegate.doDataToLister(ClientPkDelegateType.Client_showOutSelfCtr, this.ctrSelfList);
            this._opCardCnt = null;
            this.findTipInfo = null;
            this.ctrSelfList = [];
        }
    },
    autoOutSelfCardAll() {
        _.each(this.ctrSelfList, function(ctr) {
            if (!!ctr && !!ctr.getCardInfo && !!ctr.getIsChoice) {
                ctr.setChoice(true);
            }
        });
        this._eveBtnOutCard();
    },

    _eveBtnOutCard() {
        var currChoiceCardsInfo = this.getChoiceCardsInfo();
        if (0 == _.size(currChoiceCardsInfo)) {
            MsgPrompt.create('请选择正确牌型');
            return;
        }

        var isResetOutCard = true;
        if (!!window.g_room) {
            isResetOutCard = window.g_room.isResetOutCard();
        }
        if (false == isResetOutCard) {
            var _lastOutCardInfo = window.g_room.getLastOutCardInfo();
            var isOK = AIGetCard.isAllOK(_lastOutCardInfo, currChoiceCardsInfo);
            if (false == isOK) {
                MsgPrompt.create('牌型不对,请重新选泽');
                return;
            }
        } else {
            //自个主动选中的牌且自己必须出牌的情况
            var _isOk = AIOutCard.isOk(currChoiceCardsInfo);
            if (!_isOk) {
                MsgPrompt.create('牌型不对,请重新选泽');
                return;
            }
        }
        var removeCtrList = this.removeCardCtrs(currChoiceCardsInfo);
        this.resetSortByCtr();
        this.actResetSortUI();
        ClientEveDelegate.doDataToLister(ClientPkDelegateType.Clinet_gamingBtnsState, EnumOpBtn.NONE); //关闭隐藏操作按钮
        ClientEveDelegate.doDataToLister(ClientPkDelegateType.Client_outSelfCtr, removeCtrList);
        this.findTipInfo = null;
        this._opCardCnt = null;
    },

    _eveBtnTip() {
        this.actRemoveChoiceAll();
        if (null == this.findTipInfo) {
            this.findTipInfo = window.g_room.getSelfTipOutCard();
            this.currTipIdx = -1;
        }
        if (this.findTipInfo.isFind) {
            var findGroupMore = this.findTipInfo.findGroupMore;
            var maxCnt = _.size(findGroupMore);
            this.currTipIdx = this.currTipIdx <= (maxCnt - 2) ? ++this.currTipIdx : 0;
            var tipInfo = findGroupMore[this.currTipIdx];
            _.each(tipInfo.cardsInfo, function(_cardInfo) {
                _.find(this.ctrSelfList, function(ctr) {
                    if (ctr.getCardInfo().id == _cardInfo.id) {
                        ctr.doChoiceState(true);
                        return true;
                    }
                    return false;
                })
            }.bind(this));
        } else {
            window.g_room.selfNoOut();
            this.findTipInfo = null;
        }
    },

    /***接受不出牌按钮事件通知 */
    _eveBtnNoOut() {
        this.actRemoveChoiceAll();
        this.findTipInfo = null;
    },

    actRemoveChoiceAll() {
        if (this.lockTouchHand) {
            return;
        }
        _.each(this.ctrSelfList, function(ctr) {
            if (ctr.actRemoveChoice) {
                ctr.resetState();
                ctr.actRemoveChoice();
            }
        });
        this.showBankerTag();
        this._opCardCnt = null;
    },

    /***重新微调布局 */
    actResetSortUI(time, _isEasing) {
        if (this.lockTouchHand) {
            return;
        }
        var size = _.size(this.ctrSelfList);
        for (var i = 0; i < size; ++i) {
            var ctr = this.ctrSelfList[i];
            var pos = this._getItemPos(i);
            ctr.setPositionActual(pos);
            ctr.setCanTouch(true);
            var isChoice = ctr.getIsChoice();
            var y = !!isChoice ? (pos.y + ctr.getChoiceHeight()) : pos.y;
            ctr.actResetPosition(cc.v2(pos.x, y), time, _isEasing);
            ctr.setLocalZOrder(i);
        }
        this.showBankerTag();
    },

    addBottomOneCardToHand(info) {

        var cardId = info.cardId;
        var worldPos = info.worldPos;
        var scale = info.scale;
        var idx = info.idx;
        if (!this.lockTouchHand) {
            this.lockTouchHand = true;
        }
        var ctr = this.createPkHandCard(cardId);
        ctr.setChoice(true);
        ctr.setCanTouch(false);
        ctr.setPositionActual(ctr.setPosByWorldPos(worldPos));
        ctr.setScaleX(0);
        ctr.setScaleY(scale);
        var scaleT = 0.35;
        var acts = [
            cc.scaleTo(scaleT, scale, scale),
            cc.delayTime(1),
            cc.callFunc(function() {
                if (1 == idx) {
                    this.lockTouchHand = false;
                    this.resetSortByCtr();
                    this.actResetSortUI(0.5, false);
                }
            }.bind(this)),
            cc.delayTime(2),
            cc.callFunc(function() {
                ctr.setCanTouch(true);
            }.bind(this)),
        ];
        var act = cc.sequence(acts);
        ctr.doAction(act);
    },


    /***做发牌动画
     * _isAnim:false //默认不传执行动画
     */
    doSendCardAnim(_isAnim) {
        _isAnim = null == _isAnim ? true : _isAnim;
        if (_isAnim) {
            PkSound.sendCard();
        }
        ClientEveDelegate.doDataToLister(ClientPkDelegateType.Client_clearOutCardAll);
        var size = _.size(this.ctrSelfList);
        this.resetSortByCtr();
        for (var i = 0; i < size; ++i) {
            var ctr = this.ctrSelfList[i];
            ctr.setPosition(this._getInitPos());
            ctr.setLocalZOrder(i);
            ctr.setPositionActual(this._getItemPos(i));
            ctr.setCollisionSize(new cc.size(this._getItemSpaceX(), ctr.getHeight()));
            if (_isAnim) {
                ctr.actSendCard(1); //做发牌动画
            } else {
                ctr.setPosition(this._getItemPos(i));
            }
        }
        this.showBankerTag();
    },
    /***创建手牌列表 */
    createHandCardItems(cards, _isAnim) {
        this.ctrSelfList = [];
        this.node.removeAllChildren();
        var size = _.size(cards);
        for (var i = 0; i < size; ++i) {
            var cardId = cards[i];
            this.createPkHandCard(cardId);
        }
        this.doSendCardAnim(_isAnim);
    },
    /**显示庄家 */
    showBankerTag() {
        var isSelfLandlord = false;
        if (window.g_room) {
            isSelfLandlord = window.g_room.isSelfLandlord();
        }
        if (!!this.ctrSelfList && isSelfLandlord) {
            var size = _.size(this.ctrSelfList);
            if (size > 0)
                this.ctrSelfList[size - 1].setActiveLandlord(isSelfLandlord);
        }
    },
    /***创建一张手牌 */
    createPkHandCard(cardId) {
        var cardCtr = UtilGameObject.getCtrByPrefabs(this.prefabPkHandCard, this.node);
        cardCtr.refreshUIByCardId(cardId);
        cardCtr.registerTouchCancel(this._itemTouchCancel.bind(this));
        cardCtr.registerTouchMove(this._itemTouchMove.bind(this));
        cardCtr.registerTouchStart(this._itemTouchStart.bind(this));
        cardCtr.setCollisionSize(new cc.size(this._getItemSpaceX(), cardCtr.getHeight()));
        cardCtr.setActiveLandlord(false);
        this.ctrSelfList.push(cardCtr);
        return cardCtr;
    },
    getCollisionIdx(_posMouse) {
        var size = _.size(this.ctrSelfList);
        for (var i = 0; i < size; ++i) {
            var ctr = this.ctrSelfList[i];
            if (!!ctr && ctr.isCheckCollision) {
                if (ctr.isCheckCollision(_posMouse)) {
                    return i;
                }
            }
        }
        return undefined;
    },
    /***对象重新重新排序*/
    resetSortByCtr() {
        this.ctrSelfList = _.sortBy(this.ctrSelfList, function(ctr) {
            var cardInfo = ctr.getCardInfo();
            var value = cardInfo.value;
            return -value;
        });
    },
    /***提取选中的牌信息 */
    getChoiceCardsInfo() {
        var choiceCardsInfo = [];
        _.each(this.ctrSelfList, function(ctr) {
            if (!!ctr && !!ctr.getCardInfo && !!ctr.getIsChoice) {
                if (!!ctr.getIsChoice()) {
                    var cardInfo = ctr.getCardInfo();
                    choiceCardsInfo.push(cardInfo);
                }
            }
        })
        return choiceCardsInfo;
    },
    removeCardCtrs(_choiceCardsInfo) {
        var tmpSize = _.size(_choiceCardsInfo);
        var removeCtrList = _.filter(this.ctrSelfList, function(_ctr) {
            var tmpCardInfo = _ctr.getCardInfo();
            var isFind = false;
            for (var i = 0; i < tmpSize; ++i) {
                if (_choiceCardsInfo[i].id == tmpCardInfo.id) {
                    isFind = true;
                    if (!!_ctr.setCanTouch) {
                        _ctr.setCanTouch(false);
                    }
                    break;
                }
            }
            return isFind;
        }.bind(this));
        _.each(_choiceCardsInfo, function(_removeCardInfo) {
            this.ctrSelfList = _.reject(this.ctrSelfList, function(_ctr) {
                var tmpCardInfo = _ctr.getCardInfo();
                var isFind = tmpCardInfo.id == _removeCardInfo.id;
                return isFind;
            }.bind(this))
        }.bind(this));

        return removeCtrList;
    },
    /***通过索引获得获得单元对下坐标 */
    _getItemPos(idx) {
        var x = -this._getTotalWidth() * 0.5; //屏幕的宽度
        var prefabSize = this._getPrefabSize();
        x += prefabSize.width * 0.5;
        x += (idx * this._getItemSpaceX());
        var y = this._getItemPosY();
        return cc.v2(x, y);
    },
    /***获得单元对下的y坐标 */
    _getItemPosY() {
        var prefabSize = this._getPrefabSize();
        var y = this.node.height - prefabSize.height;
        return -(y *= 0.5);
    },
    /***【x坐标】单元对象间的间距
     * _itemCnt:单元格的数量 默认不传使用实际牌对象的个数
     */
    _getItemSpaceX() {
        var currCardCnt = _.size(this.ctrSelfList);
        if (currCardCnt < (this._getCardCntMax() - this._getLimitCnt())) {
            return this.fixedSpaceX;
        }
        /***铺满的需要实时计算*/
        var prefabSize = this._getPrefabSize();
        var needWidthTotal = this._getTotalWidth() - prefabSize.width;
        var itemWidth = needWidthTotal / (currCardCnt - 1) * 1.0;
        return itemWidth;
    },
    _getLimitCnt() {
        return 4;
    },
    _getTotalWidth() {
        var currCardCnt = _.size(this.ctrSelfList);
        var prefabSize = this._getPrefabSize();
        if (currCardCnt < (this._getCardCntMax() - this._getLimitCnt())) {
            var prefabSize = this._getPrefabSize();
            var _totalWidth = this.fixedSpaceX * (currCardCnt - 1) + prefabSize.width;
            return _totalWidth;
        } else {
            //铺满的情况
            var sceneSize = MgAdaptation.Inst().initSceneSize();
            return this.mainLayer.width; //sceneSize.width;

        }
    },

    /***手牌最大数量 */
    _getCardCntMax() {
        return 20;
    },

    /***主要是用于发牌动画的初始位置 */
    _getInitPos() {
        if (null == this.initItemPos) {
            var prefabSize = this._getPrefabSize();
            var x = this.mainLayer.width * 0.5 + prefabSize.width * 0.5;; //屏幕的宽度
            var y = this._getItemPosY();
            this.initItemPos = cc.v2(x, y);
        }
        return this.initItemPos;
    },

    /***预设的尺寸 */
    _getPrefabSize() {
        if (null == this.itemCardSize) {
            this.itemCardSize = new cc.size(this.prefabPkHandCard.data.width, this.prefabPkHandCard.data.height);
        }
        return this.itemCardSize;
    },

    _itemTouchStart() {
        this.touchBeignChoiceStateList = [];
        _.each(this.ctrSelfList, function(ctr) {
            if (!!ctr && ctr.getIsChoice) {
                this.touchBeignChoiceStateList.push(ctr.getIsChoice());
            }
        }.bind(this));
        this.fristIdx = null;
        this.lastMaxIdx = null;
        this.lastMinIdx = null;
        this.oldIdx = null;
        if (!!this._opCardCnt) {
            this._opCardCnt += 1;
        }
    },

    _itemTouchCancel() {
        _.each(this.ctrSelfList, function(ctr) {
            if (!!ctr && ctr.doUnLockChoice) {
                ctr.doUnLockChoice();
            }
        })
        this.fristIdx = null;
        this.lastMaxIdx = null;
        this.lastMinIdx = null;
        this.oldIdx = null;

        if (null == this._opCardCnt) {
            this._correctChoiceCards();
        }

        if (!this._opCardCnt) {
            this._opCardCnt = 1;
        }
    },

    _itemTouchMove(event) {
        var currIdx = this.getCollisionIdx(event.getLocation());
        if (undefined == currIdx) {
            return;
        }
        if (null == this.oldIdx) {
            this.fristIdx = currIdx;
            this.lastMaxIdx = currIdx;
            this.oldIdx = currIdx;
            this.lastMinIdx = currIdx;
            this.ctrSelfList[this.oldIdx].doSwitch();
        }
        if (this.oldIdx != currIdx) {
            /***记录历史最大 */
            this.lastMaxIdx = this.lastMaxIdx < currIdx ? currIdx : this.lastMaxIdx;
            this.lastMinIdx = this.lastMinIdx > currIdx ? currIdx : this.lastMinIdx;
            var needMinIdx = this.fristIdx > currIdx ? currIdx : this.fristIdx;
            var needMaxIdx = this.fristIdx < currIdx ? currIdx : this.fristIdx;
            for (var i = this.lastMinIdx; i <= this.lastMaxIdx; ++i) {
                var isChoice = this.touchBeignChoiceStateList[i];
                if (i >= needMinIdx && i <= needMaxIdx) {
                    if (!isChoice != this.ctrSelfList[i].getIsChoice()) {
                        this.ctrSelfList[i].doChoiceState(!isChoice);
                    }
                } else {
                    if (!isChoice == this.ctrSelfList[i].getIsChoice()) {
                        this.ctrSelfList[i].doChoiceState(isChoice);
                    }
                }
            }
            this.oldIdx = currIdx;
        }
    },

    /***修正选中的牌 */
    _correctChoiceCards() {
        var _currChoiceCardsInfo = [];
        _.each(this.ctrSelfList, function(ctr) {
            if (ctr && ctr.getIsChoice && ctr.getIsChoice()) {
                var _cardInfo = ctr.getCardInfo();
                _currChoiceCardsInfo.push(_cardInfo);
            }
        });
        var choiceSize = _.size(_currChoiceCardsInfo);
        if (choiceSize <= 1) {
            return;
        }
        /**========================没人要牌时自己手动选中的牌自动过滤=============================**/
        var needFixCards = null; //需要纠正的牌
        var result = FindAutoFilter.getAutoChoiceBastType(_currChoiceCardsInfo);
        if (result.isFind) {
            if (!!result.findGroup) {
                needFixCards = result.otherGroup;
            }
            if (!!result.findGroupMore) {
                var findInfo = result.findGroupMore[0];
                needFixCards = findInfo.otherGroup;
            }
        }

        if (!!needFixCards && _.size(needFixCards) > 0) {
            _.each(needFixCards, function(_fixCardInfo) {
                var id = _fixCardInfo.id;
                _.each(this.ctrSelfList, function(ctr) {
                    if (ctr && ctr.getCardInfo) {
                        var _cardInfo = ctr.getCardInfo();
                        if (_cardInfo.id == id) {
                            ctr.doSwitch();
                        }
                    }
                }.bind(this));
            }.bind(this));
        }
    }
});